<?php
namespace app\manage\controller;

use think\Controller;
use app\common\controller\BaiduService;
use app\common\controller\TengxunService;
use app\common\controller\JuliangService;
use think\Db;
use think\Exception;
use think\Log;
use think\Queue;

class Crontab extends Controller
{

    public function _initialize()
    {
        set_time_limit(0);
    }


    //商户消息 cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/sendMerMsg
    public function sendMerMsg(){
        $msg_type=3;//居中弹

        $title='销售话术合规要求通知';
        $content='抽查过程中，凡发现“话术”等存在不合规的问题，我们将终止与机构合作，据此产生的后果由对应的问题合作商机构承担，同时'.config('database')['host_sms_name'].'将对问题机构相关费用进行扣罚，即：【机构充值剩余广告费不退，机构缴纳的保证金不退】';

        if(empty($title)||empty($content)){
            return true;
        }

        $adminArr=Db::name('merchant')->where('status',1)->column('id');
        $insertData=[];
        foreach ($adminArr as $v){
            $insertData[]=['role_type'=>1,'msg_type'=>$msg_type,'a_id'=>$v,'title'=>$title,'content'=>$content];
        }

        $result = model('MsgNotice')->saveAll($insertData);
        echo '消息发送成功';
    }

    public function updateReport()
    {
        $accounts = model('Account')->getListByMap();

        foreach($accounts as $k=>$v){
            if($v['channel_id'] == 1){
                (new BaiduService())->getReportData($v['id'],1);
            }elseif ($v['channel_id'] == 2){
                (new TengxunService())->getReportData($v['id'],1);
            }elseif ($v['channel_id'] == 3){
                (new JuliangService())->getReportData($v['id'],1);
            }

            echo $v['id'].'：执行--'.date('Y-m-d H:i:s').PHP_EOL;
            Log::init(['type'=>'File','path'=>LOG_PATH,'level'=>['error']]);
            trace($v['id'].'：执行--'.date('Y-m-d H:i:s'),'error');
        }

    }


    /** 汇总每日数据
     * cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/collectDaily
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function collectDaily()
    {
        $yesterday = strtotime('-1 days');
        $start = date('Y-m-d 00:00:00',$yesterday);
        $end = date('Y-m-d 23:59:59',$yesterday);
        $time =  date('Y-m-d',$yesterday);
        $map = ['status'=>1,'create_time'=>['between',[strtotime($start),strtotime($end)]]];
        $list = model('ClueLog')->field('count(id) clue_num,count(distinct phone) clue_dis_num,sum(price) prices,push_id,mer_id,charge_type,adv_id')->where($map)->group('adv_id,push_id')->select();
        $dailys=[];
        foreach ($list as $v){
            $dailys['time']          = $time;
            $dailys['mer_id']        = $v['mer_id'];
            $dailys['adv_id']        = $v['adv_id'];
            $dailys['push_id']        = $v['push_id'];
            $dailys['clue_num']        = $v['clue_num'];
            $dailys['charge_type']        = $v['charge_type'];
            $dailys['prices']        = $v['prices'];

            $one_map = ['adv_id'=>$v['adv_id'],'push_id'=>$v['push_id'],'time'=>$time];
            $info = model('ClueStat')->getArrayByMap($one_map,false,[],false);
            if(!$info){
                $res = model('ClueStat')->isUpdate(false)->data($dailys, true)->save($dailys);
                if($res){
//                    Db::name('merchant')->where('id',$dailys['mer_id'])->setDec('balance',$dailys['prices']);
                    echo $time.'【'.$v['adv_id'].'】【'.$v['push_id'].'】汇总数据保存成功'.'<br>';
                }else{
                    echo $time.'【'.$v['adv_id'].'】【'.$v['push_id'].'】汇总数据保存失败'.'<br>';
                }

            }else{
                echo $time.'【'.$v['adv_id'].'】【'.$v['push_id'].'】汇总数据已存在'.'<br>';
            }
        }

    }

    /**
     * 重新推送当然线索
     * cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/dayRePushClue
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function dayRePushClue(){
        // 1.当前任务将由哪个类来负责处理。
        // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
        $jobHandlerClassName  = 'app\job\DayReClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "DayReClue";

        $yesterday=strtotime(date('Y-m-d',strtotime('-2 days')));
        $clueArr=model('Clue')->field('id')->where('create_time','>=',$yesterday)->where('status',0)->select();

        $time2wait=mt_rand(120,300);
        foreach ($clueArr as $v) {
            echo json_encode(['id'=>$v['id'],'time'=>time()+$time2wait]);
            $jobData = ['id'=>$v['id']];
            $isPushed = Queue::later($time2wait, $jobHandlerClassName, $jobData, $jobQueueName);
            $time2wait += mt_rand(120,300);
        }
    }


    /**
     * 每天0点统计昨天导入线索成本
     * cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/ClueCostLog
     */
    public function ClueCostLog(){

        $list=model('Clue')->alias('a')->field('a.adv_id,pro_id,city,count(id) num,sum(price) price')->whereTime('create_time','yesterday')->where('price','>',0)
            ->group('a.adv_id,pro_id,city')
            ->select();

        Db::startTrans();

        $insertData=[];
        $time=date("Y-m-d",strtotime("-1 day"));
        foreach ($list as $v){
            $account=Db::name('account')->where('adv_id',$v['adv_id'])->find();
            $clueNum=$v['num'];
            $trueCost1=bcdiv($v['price'],bcadd(1,$account['clue_rate']/100,4),3);
            if($clueNum>0){
                $trueCost2=bcdiv($trueCost1,$clueNum,3);
                $changeCost=bcdiv($v['price'],$clueNum,3);
            }else{
                $trueCost2=0;
                $changeCost=0;
            }

            $insertData[]=[
                'account_id'=>$account['id'],
                'pro_id'=>$v['pro_id'],
                'time'=>$time,
                'city'=>$v['city'],
                'exposure_val'=>0,
                'click_val'=>0,
                'money'=>$v['price'],
                'transform_val'=>$clueNum,
                'remark'=>'',
                'clue_num'=>$clueNum,
                'change_cost'=>$changeCost,
                'true_cost'=>$trueCost2,
                'true_consume'=>$trueCost1,
                'create_time'=>time(),
                'type'=>2,
            ];
        }

        if($insertData){
            model('ClueCostLog')->insertAll($insertData);
            Db::commit();
            echo $time.'插入成功';
        }else{
            Db::rollback();
            echo $time.'插入失败';
        }
    }

    /**
     * 每天0点统计昨天导入线索成本
     * cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/ClueCostLog2
     */
    public function ClueCostLog2(){
        $list=model('Clue')->alias('a')->field('a.adv_id,pro_id,city,count(id) num,sum(price) price')->whereTime('create_time','yesterday')->where('adv_id',9521)
            ->group('a.adv_id,pro_id,city')
            ->select();

        Db::startTrans();

        $insertData=[];
        $time=date("Y-m-d",strtotime("-1 day"));
        foreach ($list as $v){
            $account=Db::name('account')->where('adv_id',$v['adv_id'])->find();
            $clueNum=$v['num'];
            $trueCost1=bcdiv($v['price'],bcadd(1,$account['clue_rate']/100,4),3);
            if($clueNum>0){
                $trueCost2=bcdiv($trueCost1,$clueNum,3);
                $changeCost=bcdiv($v['price'],$clueNum,3);
            }else{
                $trueCost2=0;
                $changeCost=0;
            }

            $insertData[]=[
                'account_id'=>$account['id'],
                'pro_id'=>$v['pro_id'],
                'time'=>$time,
                'city'=>$v['city'],
                'exposure_val'=>0,
                'click_val'=>0,
                'money'=>$v['price'],
                'transform_val'=>$clueNum,
                'remark'=>'',
                'clue_num'=>$clueNum,
                'change_cost'=>$changeCost,
                'true_cost'=>$trueCost2,
                'true_consume'=>$trueCost1,
                'create_time'=>time(),
                'type'=>2,
            ];
        }

        if($insertData){
            model('ClueCostLog')->insertAll($insertData);
            Db::commit();
            echo $time.'插入成功';
        }else{
            Db::rollback();
            echo $time.'插入失败';
        }
//        $list=model('Clue')->alias('a')->field('FROM_UNIXTIME(create_time,"%Y-%m-%d") as days,a.adv_id,pro_id,city,count(id) num,sum(price) price,create_time')->where('adv_id',9521)
////            ->where('create_time','between',[strtotime('2023-12-20'),strtotime('2023-12-20 23:59:59')])
//            ->whereTime('create_time','yesterday')
//            ->group('days,a.adv_id,pro_id,city')
//            ->select();
//
//        Db::startTrans();
//
//        $insertData=[];
//        foreach ($list as $v){
//            $account=Db::name('account')->where('adv_id',$v['adv_id'])->find();
//            $clueNum=$v['num'];
//            $trueCost1=bcdiv($v['price'],bcadd(1,$account['clue_rate']/100,4),3);
//            if($clueNum>0){
//                $trueCost2=bcdiv($trueCost1,$clueNum,3);
//                $changeCost=bcdiv($v['price'],$clueNum,3);
//            }else{
//                $trueCost2=0;
//                $changeCost=0;
//            }
//            $time=$v['days'];
//
//            $insertData[]=[
//                'account_id'=>$account['id'],
//                'pro_id'=>$v['pro_id'],
//                'time'=>$time,
//                'city'=>$v['city'],
//                'exposure_val'=>0,
//                'click_val'=>0,
//                'money'=>$v['price'],
//                'transform_val'=>$clueNum,
//                'remark'=>'',
//                'clue_num'=>$clueNum,
//                'change_cost'=>$changeCost,
//                'true_cost'=>$trueCost2,
//                'true_consume'=>$trueCost1,
//                'create_time'=>time(),
//                'type'=>2,
//            ];
//        }
//
//        if($insertData){
//            model('ClueCostLog')->insertAll($insertData);
//            Db::commit();
//            echo '插入成功';
//        }else{
//            Db::rollback();
//            echo '插入失败';
//        }
    }


    /**
     * 每天0点统计昨天导入线索成本
     * cd /www/wwwroot/www.fengzhu.top/public/ && php index.php manage/crontab/ClueCostLog2
     */
//    public function testBug(){
//        $jobHandlerClassName  = 'app\job\SubCluePush@fire';
//        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
//        $jobQueueName     = "SubCluePush";
//
//        $jobData = ['mer_id'=>313,'clue_id'=>12828];
//        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
//    }

    /**
     * 统计 线索城市满足率
     * 每天0点运行
     */
    public function statCity()
    {
        $redis = redis();
        $lock_key = config('config.prefix') . "crontab_stat_push_city";
        if ($redis->get($lock_key)) {
            echo "当天不可重复统计\r\n"; exit;
        }
        $redis->setex($lock_key, 86300, 1);

        echo "开始时间". date('Y-m-d H:i:s'). "\r\n";
        $datetime = date("Y-m-d");
        $infos = \db('push')
            ->alias('a')
            ->join('merchant b','b.id=a.mer_id')
            ->field('count(a.id) num,city,sum(up_limit) up_limit, pro_id')
            ->where('a.status', 1)
            ->where('b.status', 1)
            ->where('a.start_time', "<=", $datetime)
            ->where('a.end_time', ">=", $datetime)
            ->where('a.delete_time', null)
            ->group('city,pro_id')
            ->select();

        $insertsql = [];
        $today = date('Y-m-d');
        $time = time();
        foreach ($infos as $v) {
            $insert = [
                'create_date' => $today,
                'city' => $v['city'],
                'pro_id' => $v['pro_id'],
                'push_num' => $v['num'],
                'accept_limit_num' => $v['up_limit'],
                'create_time' => $time,
                'update_time' => $time,
            ];
            $insertsql[] = \db('stat_city')->fetchSql(true)->insert($insert);
        }
        if (!empty($insertsql)) {
            \db()->batchQuery($insertsql);
        } else {
            echo "数据为空". "\r\n";
        }
        echo "结束时间". date('Y-m-d H:i:s'). "\r\n";
    }

    /**
     * 统计按周期计算成本
     */
//    public function stat_week_price()
//    {
//        require ROOT_PATH."timertask/stat_week_price.php";
//    }
//
//    /**
//     * 每日凌晨0点 生成分发规则记录
//     */
//    public function insert_push_record()
//    {
//        require ROOT_PATH."timertask/insert_push_record.php";
//    }

    /**
     * 每3分钟运行 重新推送当然线索
     */
    public function repeat_push_clue()
    {
        require ROOT_PATH."timertask/repeat_push_clue.php";
    }

}